package org.cqu_proj.demo.service;

import org.cqu_proj.demo.dao.RatingRepository;
import org.cqu_proj.demo.dto.ResponseResult;
import org.cqu_proj.demo.entity.Rating;
import org.sparkproject.jetty.util.statistic.RateCounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

@Service
public class RatingService {
    private final RatingRepository ratingRepository;
    @Autowired
    public RatingService(RatingRepository ratingRepository) {
        this.ratingRepository = ratingRepository;
    }

    //查询一个用户下所有的评分记录
    public List<Rating> getRatingsByUserId(int userId) {
        return ratingRepository.findByUserId(userId);
    }

    public ResponseResult<Rating> saveOrUpdateRating(int userId, int movieId, Double rating) {
        Rating existingRating = ratingRepository.findByUserIdAndMovieId(userId, movieId);
        boolean isSave=true;
        if (existingRating != null) {
            // 更新现有评分
            existingRating.setRating(rating);
            existingRating.setTimestamp(Instant.now().getEpochSecond()); // 更新时间戳
            isSave=false;
        } else {
            // 新增评分
            existingRating = new Rating();
            existingRating.setUserId(userId);
            existingRating.setMovieId(movieId);
            existingRating.setRating(rating);
            existingRating.setTimestamp(Instant.now().getEpochSecond());
        }
        Rating newSave= ratingRepository.save(existingRating);
        if(isSave)  return  new ResponseResult<>(200,"是新评论",newSave);
        else  return  new ResponseResult<>(201,"是更新的评分",newSave);
    }

}
